package neichuan.message;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.Map;

public class MessageDecoder extends LengthFieldBasedFrameDecoder {

    public MessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
    }

    public MessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
    }

    public MessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast);
    }

    public MessageDecoder(ByteOrder byteOrder, int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
        super(byteOrder, maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast);
    }

    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        //获得一段可以构成Message的完整的数据
        in= (ByteBuf)super.decode(ctx, in);
        if(in==null){
            return null;
        }

        //构造Message
        int type=in.readInt();
        int content_length=in.readInt();
        int headerSize=in.readInt();
        byte[] buffer;

        Map<Integer,byte[]> headers=new HashMap<>();
        for(int i=0;i<headerSize;i++){
            int headDataLength=in.readInt();
            int key=in.readInt();
            buffer=new byte[headDataLength];
            in.readBytes(buffer);
            headers.put(key,buffer);
        }
        buffer=new byte[content_length];
        in.readBytes(buffer);
        in.release();
        return new Message(type,headers,buffer);
    }

}
